package jp.co.dailyReport.search.action;

import java.io.IOException;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.DynaActionForm;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.search.SearchWeeklyReport;
import jp.co.dailyReport.search.SearchConditionOfWeeklyReport;
import jp.co.dailyReport.search.SearchWeeklyReportManager;

/**
 * 週報検索の検索結果一覧ページのページ変えリンク、
 * 週報検索ページの「検索」ボタン
 * が押されたときの処理を管理するクラスです。
 */
public class SearchWeeklyReportConditionAction extends Action {

	private static Logger log = Logger.getLogger(SearchWeeklyReportConditionAction.class);

	/**
	 * 週報検索の検索結果一覧ページのページ変えリンク、週報検索ページの「検索」ボタン
	 * が押されたときの処理を行います。<BR><BR>
	 * 「検索」ボタンが押された場合の処理：<BR>
	 * 検索条件の入力チェックを行います。
	 * 検索条件にあった検索結果を取得します。<BR>
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		 throws IOException, ServletException {

		log.debug("SearchWeeklyReportConditionAction start");
		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		DynaActionForm searchConditionOfWeeklyReportActionForm = (DynaActionForm) form;
		SearchWeeklyReport[] searchWeeklyReport = null;
		ArrayList searchWeeklyReportList = new ArrayList();
		String target = null;
		ActionErrors errors = new ActionErrors();

		String keyWord = ((String)searchConditionOfWeeklyReportActionForm.get("keyWord")).trim();
		int customerId = ((Integer)searchConditionOfWeeklyReportActionForm.get("customerId")).intValue();
		int pLStaffId = ((Integer)searchConditionOfWeeklyReportActionForm.get("pLStaffId")).intValue();
		int projectId = ((Integer)searchConditionOfWeeklyReportActionForm.get("projectId")).intValue();
		int maxPage = ((Integer)searchConditionOfWeeklyReportActionForm.get("maxPage")).intValue();
		int nowPage = ((Integer)searchConditionOfWeeklyReportActionForm.get("nowPage")).intValue();
		Integer searchWorkDateStartYear = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateStartYear");
		Integer searchWorkDateStartMonth = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateStartMonth");
		Integer searchWorkDateStartWeek = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateStartWeek");
		Integer searchWorkDateEndYear = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateEndYear");
		Integer searchWorkDateEndMonth = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateEndMonth");
		Integer searchWorkDateEndWeek = (Integer)searchConditionOfWeeklyReportActionForm.get("searchWorkDateEndWeek");

		//検索条件情報設定
		SearchConditionOfWeeklyReport searchConditionOfWeeklyReport = new SearchConditionOfWeeklyReport();
		searchConditionOfWeeklyReport.setKeyWord(keyWord);
		searchConditionOfWeeklyReport.setCustomerId(customerId);
		searchConditionOfWeeklyReport.setPLStaffId(pLStaffId);
		searchConditionOfWeeklyReport.setProjectId(projectId);
		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
		int searchWorkDateStart = 0;
		if(searchWorkDateStartYear.intValue()!=0 && searchWorkDateStartMonth.intValue()!=0 && searchWorkDateStartWeek.intValue()!=0){
			Calendar cal = Utilities.getEWeekCalendarDate(searchWorkDateStartYear,searchWorkDateStartMonth,searchWorkDateStartWeek);
			searchConditionOfWeeklyReport.setSearchWorkDateStart(cal);
			searchWorkDateStart = Integer.parseInt(df.format(cal.getTime()));
		}
		int searchWorkDateEnd = 0;
		if(searchWorkDateEndYear.intValue()!=0 && searchWorkDateEndMonth.intValue()!=0 && searchWorkDateEndWeek.intValue()!=0){
			Calendar cal = Utilities.getEWeekCalendarDate(searchWorkDateEndYear,searchWorkDateEndMonth,searchWorkDateEndWeek);
			searchConditionOfWeeklyReport.setSearchWorkDateEnd(cal);
			searchWorkDateEnd = Integer.parseInt(df.format(cal.getTime()));
		}

		//週報検索条件が全てなしの場合のチェック
		int conditionStatus = 0;
		if(keyWord==null){
			conditionStatus++;
		}else{
			if(keyWord.length()==0){
				conditionStatus++;
			}
		}
		if(customerId==0){
			conditionStatus++;
		}
		if(pLStaffId==0){
			conditionStatus++;
		}
		if(projectId==0){
			conditionStatus++;
		}
		if(searchWorkDateStart==0){
			conditionStatus++;
		}
		if(searchWorkDateEnd==0){
			conditionStatus++;
		}

		/* 検索条件入力判定 */
		if(conditionStatus != SearchConditionOfWeeklyReport.CONDITION_STATUS){
			/* 検索期間条件判定 */
			if(searchWorkDateStart > searchWorkDateEnd && searchWorkDateEnd!=0){
				target = "error";
				errors.add("errors.search.weeklyReportCondition.invalid",new ActionError("errors.search.weeklyReportCondition.invalid"));
				saveErrors(request,errors);
			}else{
				target = "list";
				try {
					if(request.getParameter("search")!=null){
						session.removeAttribute("searchWeeklyReportResult");
						searchWeeklyReport = SearchWeeklyReportManager.load(staff,searchConditionOfWeeklyReport);
						session.setAttribute("searchWeeklyReportResult",searchWeeklyReport);
					}else{
						searchWeeklyReport = (SearchWeeklyReport[])session.getAttribute("searchWeeklyReportResult");
					}
				} catch(DataUnavailableException due) {
					log.error(due.getMessage());
				}
				if(maxPage == 0){
					int searchResultCount = searchWeeklyReport.length;
					maxPage = searchResultCount/SearchConditionOfWeeklyReport.PAGE_COUNT;
					if(searchResultCount%SearchConditionOfWeeklyReport.PAGE_COUNT!=0){
						maxPage = maxPage + 1;
					}
					searchConditionOfWeeklyReportActionForm.set("maxPage", new Integer(maxPage));
					if(maxPage != 0){
						nowPage = 1;
						searchConditionOfWeeklyReportActionForm.set("nowPage", new Integer(1));
					}
				}
				if(maxPage != 0){
					if(nowPage < maxPage){
						for(int i = ((nowPage-1)*SearchConditionOfWeeklyReport.PAGE_COUNT);i<(nowPage*SearchConditionOfWeeklyReport.PAGE_COUNT);i++){
							searchWeeklyReportList.add(searchWeeklyReport[i]);
						}
					}else if(nowPage==maxPage){
						for(int i = ((nowPage-1)*SearchConditionOfWeeklyReport.PAGE_COUNT);i<searchWeeklyReport.length;i++){
							searchWeeklyReportList.add(searchWeeklyReport[i]);
						}
					}
				}
				request.setAttribute("searchWeeklyReport", (SearchWeeklyReport[])searchWeeklyReportList.toArray(new SearchWeeklyReport[0]));
				//週報検索結果のリンク先ページに渡すパラメータ設定
				Map params = new HashMap();
				params.put("keyWord", "keyWord");
				params.put("customerId", String.valueOf(customerId));
				params.put("pLStaffId", String.valueOf(pLStaffId));
				params.put("projectId", String.valueOf(projectId));
				params.put("maxPage", String.valueOf(maxPage));
				params.put("searchWorkDateStartYear", searchWorkDateStartYear);
				params.put("searchWorkDateStartMonth", searchWorkDateStartMonth);
				params.put("searchWorkDateStartWeek", searchWorkDateStartWeek);
				params.put("searchWorkDateEndYear", searchWorkDateEndYear);
				params.put("searchWorkDateEndMonth", searchWorkDateEndMonth);
				params.put("searchWorkDateEndWeek", searchWorkDateEndWeek);
				request.setAttribute("params", params);
			}
		}else{
			target = "error";
			errors.add("errors.search.weeklyReportCondition.required",new ActionError("errors.search.weeklyReportCondition.required"));
			saveErrors(request,errors);
		}

		log.debug("SearchWeeklyReportConditionAction end");
		return mapping.findForward(target);
	}
}
